<template>
  <div class="home fixed bottom-162rpx left-0 right-0 top-0 max-h-screen min-h-screen bg-hex-ffffff">
    <image
      :src="`${cdnUrl}/imgs/detail/bg.png${imgVersion}`"
      class="pointer-events-none absolute left-0 right-0 top-0 z--1 w-100%"
      mode="scaleToFill"
    />
    <div
      id="upBox"
      :style="{ paddingTop: `${searchBarTop}px` }"
      class="z-9 px-28rpx">
      <div class="flex items-start justify-between">
        <image
          :src="`${cdnUrl}/imgs/square/logo.png${imgVersion}`"
          mode="scaleToFill"
          class="h-82rpx w-204rpx"
        />
        <image
          :src="`${cdnUrl}/imgs/home/search.png${imgVersion}`"
          mode="scaleToFill"
          class="mr-200rpx h-64rpx w-64rpx"
          :style="{ marginRight: `${rightBar}px` }"
          @click="navTo('/pages-tea/search')"
        />
      </div>
      <div class="mb-30rpx flex items-center justify-between">
        <div>

          <div class="mb-8rpx flex items-center" @click="navGoTo">
            <text class="text-28rpx font-600 text-hex-333333">{{ location.selectStores.storeName }}</text>
            <image
              :src="`${cdnUrl}/svgicons/home/more.svg${imgVersion}`"
              mode="scaleToFill"
              class="h-32rpx w-32rpx"
            />
          </div>
          <div v-if="isNotNilOrEmpty(location.selectStores.distance)" class="text-24rpx text-hex-5A736A">距离您{{ formatDistance(location.selectStores.distance) }}</div>
          <div v-else class="mb-8rpx flex items-center" @click="openPosition">
            <text class="text-28rpx font-600 text-hex-333333">无法获取定位信息</text>
            <image
              :src="`${cdnUrl}/svgicons/home/more.svg${imgVersion}`"
              mode="scaleToFill"
              class="h-32rpx w-32rpx"
            />
          </div>
        </div>
        <div class="box-border h-64rpx w-200rpx flex rounded-72rpx bg-hex-F1F1F1 p-4rpx">
          <div
            v-for="item in toptablist"
            class="h-56rpx w-96rpx text-center text-28rpx leading-56rpx text-hex-999999"
            :class="{ 'text-hex-ffffff bg-hex-ABCD03 rounded-72rpx': location.selfPickup===item.id }"
            @click="changeIndex(item.id)">
            {{ item.text }}
          </div>
        </div>
      </div>
      <div v-if="noticeList" class="relative mb-36rpx w-100% text-24rpx text-hex-5A736A">
        <div class="h-20px flex items-center">通知
          <span class="ml-8rpx inline-block h-20rpx w-3rpx bg-hex-5A736A" />
        </div>
        <div class="absolute right-30% top-0 z-99999 w-60%">
          <uni-notice-bar :speed="36" color="#5A736A" background-color="transparent" scrollable :text="noticeList.noticeContent" />
        </div>
      </div>
      <!-- {{ noticeList.noticeContent }} -->
      <div v-if="!loginStore.roleId" class="relative">
        <div>
          <image
            class="pointer-events-none absolute left-0 right-0 top-0 z--1 h-110rpx w-100%"
            :src="`${cdnUrl}/imgs/squaremy/background-block.png${imgVersion}`"
            mode="scaleToFill"
          />
        </div>
        <div class="flex items-center justify-between px-32rpx pt-18rpx">
          <div class="text-24rpx text-hex-ffffff">Hi,👏欢迎来到心悦</div>
          <!-- <div v-if="userInfo.user.avatarUrl"><image
            :src="userInfo.user.avatarUrl"
            mode="scaleToFill"
            class="z-99 h-70rpx w-70rpx rounded-50%"
          /></div> -->
          <!-- <div v-if="userInfo.user?.avatarUrl===undefined" class="relative h-52rpx w-208rpx flex items-center justify-center rounded-68rpx bg-hex-33a07d text-24rpx text-hex-fff" -->
          <div class="relative h-52rpx w-208rpx flex items-center justify-center rounded-68rpx bg-hex-abcd03 text-24rpx text-hex-fff"
               @click="goLogin">
            <div>登录/</div>
            <div>注册</div>
            <image
              :src="`${cdnUrl}/imgs/home/teaPerson.png${imgVersion}`"
              mode="scaleToFill"
              class="pointer-events-none absolute bottom-0 h-70rpx w-86rpx -left-10rpx"
            />
          </div>
        </div>
      </div>
      <div v-else class="relative">
        <div>
          <image
            :src="`${cdnUrl}/imgs/healthProgramme/health.png${imgVersion}`"
            mode="scaleToFill"
            class="absolute right-32rpx z--10 h-95rpx w-100rpx -top-90rpx"
          />
          <image
            class="pointer-events-none absolute left-0 right-0 top-0 z--1 h-110rpx w-100%"
            :src="`${cdnUrl}/imgs/squaremy/background-block.png${imgVersion}`"
            mode="scaleToFill"
          />
        </div>
        <div class="flex items-center justify-between px-32rpx pt-18rpx">
          <div class="flex items-center">
            <div><image
              :src="userInfo.user.avatarUrl"
              mode="scaleToFill"
              class="mr-10rpx h-42rpx w-42rpx rounded-50%"
            /></div>
            <div class="text-24rpx text-hex-ffffff">Hi,👏欢迎来到心悦</div>
          </div>
          <div class="relative text-24rpx text-hex-fff">
            {{ userInfo.user.nickname }}
          </div>
        </div>
      </div>
    </div>
    <div
      v-if="rightGoodsList"
      id="downBox"
      class="relative">
      <image
        :src="`${cdnUrl}/imgs/home/bg2.png${imgVersion}`"
        mode="scaleToFill"
        class="pointer-events-none absolute left-0 right-0 h-180rpx w-100% -top-38rpx -z-1"
      />
      <div class="flex justify-around">
        <div v-for="item in tabList" class="mt-45rpx text-28rpx text-hex-7c8699" @click="changetabindex(item.id)">
          <div v-if="tabindex===item.id" class="flex flex-col items-center">
            <div class="flex">
              <div>
                <image
                  :src="`${cdnUrl}/svgicons/home/tea.svg${imgVersion}`"
                  class="h-52rpx w-52rpx"
                  mode="scaleToFill"
                />
              </div>
              <div class="flex flex-col items-center justify-center">
                <div class="text-32rpx font-600 text-hex-383B34">{{ item.text }}</div>
                <div>
                  <image
                    :src="`${cdnUrl}/svgicons/home/active.svg${imgVersion}`"
                    class="h-36rpx w-64rpx -mt-20rpx"
                    mode="scaleToFill"
                  />
                </div>
              </div>
            </div>
            <div class="triangle -mt-28rpx" />
          </div>
          <div v-else>{{ item.text }}</div>
        </div>
      </div>
      <!-- 茶饮菜单 -->
      <div
        v-if="tabindex===0"
        class="relative w-100%">
        <div
          :style="`height:${downHeight}px`"
          class="absolute bottom-0rpx left-0 top-0 box-border w-188rpx rounded-tl-32rpx bg-hex-ffffff pt-20rpx">
          <scroll-view
            id="scrollBox"
            :style="`height:${scrollHeight}px`"
            :scroll-top="leftScrollHeight"
            class="box-border"
            :scroll-y="true"
            :scroll-with-animation="true"
            @scroll="leftScroll"
          >
            <div
              v-for="(item, index) in rightGoodsList"
              class="mb-20rpx h-100rpx flex items-center justify-center text-28rpx text-hex-999999"
              :class="{ 'activecolor font-600 rounded-tr-50rpx rounded-br-50rpx bg-hex-F5F5F5': leftTabIndex===item.id }"
              @click="changeleftTabIndex(item.id, index)"
            >
              <div
                class="relative w-100% flex items-center justify-center"
              >
                <div v-if="leftTabIndex===item.id"
                     class="borderShadow absolute left-0 mr-20rpx h-46rpx w-6rpx rounded-r-32rpx bg-hex-ABCD03" />
                <div v-if="item.image">
                  <image
                    :src="item.image"
                    mode="scaleToFill"
                    class="h-60rpx w-30rpx"
                  />
                </div>
                <div>{{ item.name }}</div>
                <div v-if="item.new"
                     class="scale7 absolute right-0 box-border rounded-16rpx rounded-bl-0rpx bg-hex-F4B265 px-8rpx py-2rpx text-hex-ffffff -top-28rpx"
                >NEW</div>
                <div v-if="item.hot"
                     class="scale7 absolute right-0 box-border rounded-16rpx rounded-bl-0rpx bg-hex-F17171 px-8rpx py-2rpx text-hex-ffffff -top-28rpx"
                >HOT</div>
              </div>
            </div>
          </scroll-view>
          <div class="h-262rpx" />
        </div>
        <div
          :style="`height:${downHeight}px`"
          class="absolute bottom-0rpx left-188rpx right-0 top-0 box-border rounded-tr-32rpx bg-hex-ffffff px-32rpx pt-20rpx">
          <div id="swiperHight">
            <!-- <swiper autoplay circular class="h-190rpx">
              <swiper-item v-for="item in 2" class="overflow-hidden rounded-32rpx -z-9">
                <image
                  :src="`${cdnUrl}/svgicons/home/banner.svg${imgVersion}`"
                  class="h-190rpx w-100% rounded-32rpx"
                  mode="scaleToFill"
                />
              </swiper-item>
            </swiper> -->
          </div>
          <div>
            <div class="relative">
              <div
                v-if="Number(scrollLength)>50"
                class="absolute z-9 h-40rpx w-100% flex items-center bg-hex-ffffff py-32rpx text-28rpx font-600 text-hex-333333 -top-4rpx">
                <div v-if="rightGoodsList[leftIndex]?.image">
                  <image
                    :src="rightGoodsList[leftIndex]?.image"
                    mode="scaleToFill"
                    class="h-60rpx w-30rpx"
                  /></div>
                <div>{{ rightGoodsList[leftIndex].name }}</div>
              </div>
            </div>
            <scroll-view
              id="scrollBox"
              :style="`height:${scrollHeight}px`"
              class="box-border"
              :scroll-y="true"
              :scroll-into-view="toView"
              :scroll-with-animation="true"
              @scroll="onScroll"
            >
              <div
                v-for="item in rightGoodsList"
                :id="item.id"
                :key="item.id"
              >
                <div v-if="item.swiperList">
                  <swiper v-if="bannerList" autoplay circular class="h-190rpx">
                    <swiper-item v-for="swip in bannerList" class="overflow-hidden rounded-32rpx -z-9">
                      <image
                        :src="swip.imageUrl"
                        class="h-190rpx w-100% rounded-32rpx"
                        mode="scaleToFill"
                      />
                    </swiper-item>
                  </swiper>
                </div>
                <div class="h-40rpx flex items-center py-32rpx text-28rpx font-600 text-hex-333333">
                  <div v-if="item.image"><image
                    :src="item.image"
                    mode="scaleToFill"
                    class="h-60rpx w-30rpx"
                  /></div>
                  <div>{{ item.name }}</div>
                </div>
                <div v-if="item.productList">
                  <div
                    v-for="itm in item.productList"
                  >
                    <div
                      v-if="itm.stock>0"
                      class="mb-32rpx flex"
                      @click="goDetail(itm.unionFlag, itm.productId)">
                      <div 
                        class="relative mr-3% mt-24rpx h-180rpx w-180rpx overflow-hidden rounded-16rpx">
                        <image
                          class="absolute left-50% top-50% h-180rpx w-180rpx rounded-16rpx"
                          style="transform: translate(-50%, -50%);" :src="itm.productImage" mode="aspectFill" />
                      </div>
                      <div class="w-65%">
                        <div class="mb-8rpx text-28rpx font-600 text-hex-333333">{{ itm.productName }}</div>
                        <!-- <div class="mb-10rpx flex">
                        <div
                          v-if="itm.new===1"
                          class="mr-16rpx box-border h-34rpx flex items-center justify-center rounded-4rpx bg-hex-F4B265 px-4rpx text-24rpx text-hex-ffffff"
                        >
                          新品饮
                        </div>
                        <div
                          v-if="itm.hot===1"
                          class="mr-16rpx box-border h-34rpx flex items-center justify-center rounded-4rpx bg-hex-F17171 px-4rpx text-24rpx text-hex-ffffff"
                        >
                          热销饮
                        </div>
                        <div class="h-32rpx flex items-center justify-center border-1rpx border-hex-7c8699 rounded-4rpx border-solid px-4rpx text-20rpx text-hex-7c8699">可做热饮</div>
                      </div> -->
                        <div v-if="itm.goodsLabel" class="mb-10rpx truncate text-24rpx text-hex-7c8699">{{ itm.goodsLabel }}</div>
                        <div class="mb-18rpx flex items-center text-24rpx text-hex-7c8699">
                          <div v-if="itm.productIntro" class="truncate">{{ itm.productIntro }}</div>
                        </div>
                        <div class="flex justify-between">
                          <div class="text-28rpx text-hex-333333">¥{{ itm.productPrice }}</div>
                          <div class="relative">
                            <image
                              :src="`${cdnUrl}/svgicons/home/add.svg${imgVersion}`"
                              mode="scaleToFill"
                              class="h-66rpx w-66rpx"
                            />
                            <div v-if="Number(itm.userWaitBuyAmount)>0" class="font-numberFont absolute right-0 box-border min-h-36rpx min-w-36rpx flex items-center justify-center border-2rpx border-hex-ffffff rounded-50% border-solid bg-hex-C1A670 text-24rpx text-hex-ffffff -top-22rpx">{{ itm.userWaitBuyAmount }}</div>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div
                      v-if="itm.stock===0"
                      class="mb-32rpx flex">
                      <div class="mr-24rpx h-180rpx w-180rpx flex items-center justify-center rounded-26rpx bg-hex-F5F3F0">
                        <image
                          :src="itm.productImage"
                          mode="scaleToFill"
                          class="h-180rpx w-180rpx rounded-26rpx"
                        />
                      </div>
                      <div class="w-65%">
                        <div class="mb-8rpx text-28rpx font-600 text-hex-E0E0E0">{{ itm.productName }}</div>
                        <div v-if="itm.goodsLabel" class="mb-10rpx truncate text-24rpx text-hex-E0E0E0">{{ itm.goodsLabel }}</div>
                        <div class="mb-18rpx flex items-center text-24rpx text-hex-E0E0E0">
                          <div v-if="itm.productIntro" class="truncate">{{ itm.productIntro }}</div>
                        </div>
                        <div class="flex justify-between">
                          <div class="text-28rpx text-hex-E0E0E0">¥{{ itm.productPrice }}</div>
                          <div class="flex items-center justify-center">
                            <div class="h-44rpx w-44rpx flex items-center justify-center rounded-50% bg-hex-F5F3F0 text-38rpx text-hex-ffffff">
                              +
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <div v-if="item.productList.length===0" class="flex flex-col items-center justify-center">
                  <image
                    :src="`${cdnUrl}/imgs/noOpen/noText.png${imgVersion}`"
                    mode="scaleToFill"
                    class="h-300rpx w-300rpx"
                  />
                  <div class="mb-64rpx text-28rpx text-hex-7C8699">暂无饮品</div>
                </div>
              </div>
              <div class="h-162rpx" />
            </scroll-view>
          </div>
        </div>
      </div>
      <!-- 周边商品 -->
      <div
        v-if="tabindex===1"
        class="scrolldemo box-border h-[calc(100vh-574rpx)] overflow-y-auto rounded-t-32rpx bg-hex-ffffff py-32rpx pb-120rpx">
        <div v-if="roundGoodsList" class="mx-32rpx">
          <s-waterfall :datalist="roundGoodsList" :column="2">
            <template #default="{ item }">
              <!-- <div v-for="item in roundGoodsList" class="flex"> -->
              <div class="mb-24rpx box-border rounded-32rpx pr-32rpx" @click.stop="roundeGoDetail(item)">
                <div class="bg-water w-326rpx flex items-center justify-center rounded-xl bg-hex-FAF9F8">
                  <image
                    class="will-change h-100% w-100% rounded-24rpx"
                    lazy-load
                    :src="item.productImage" mode="widthFix" />
                </div>
                <text class="multiLine-hiddle mx-10rpx mt-10rpx inline-block">{{ item.productName }}</text>
                <text class="mb-26rpx inline-block bg-hex-FFF2E3 px-4rpx py-2rpx text-20rpx text-hex-E89C43">{{ item.goodsLabel }}</text>
                <div>
                  <text class="mr-10rpx text-30rpx font-600 text-hex-ff4d4e">¥{{ item.productPrice }}</text>
                  <text class="text-26rpx text-hex-999999 line-through">¥{{ item.cost }}</text>
                </div>
                <div class="mb-32rpx flex items-center justify-between">
                  <div class="mr-32rpx text-hex-999999 line-through">已售{{ item.saleNum??0 }}</div>
                  <image
                    :src="`${cdnUrl}/svgicons/home/add.svg${imgVersion}`"
                    class="mt--20rpx h-64rpx w-64rpx"
                    mode="scaleToFill"
                  />
                </div>
              </div>
              <!-- </div> -->
            </template>
          </s-waterfall>
        </div>
        <div v-if="roundGoodsList.length===0" class="flex flex-col items-center justify-center">
          <image
            :src="`${cdnUrl}/imgs/noOpen/noText.png${imgVersion}`"
            mode="scaleToFill"
            class="h-300rpx w-300rpx"
          />
          <div class="mb-64rpx text-28rpx text-hex-7C8699">暂无饮品</div>
        </div>
      </div>
    </div>
    <div v-if="rightGoodsList.length===0">
      <div
        class="mt-200rpx flex items-center justify-center">
        <div>
          <image
            class="h-364rpx w-364rpx"
            :src="`${cdnUrl1}/imgs/xy/other/noneeattention.png${imgVersion}`"
            mode="scaleToFill"
          />
          <div class="text-center text-28rpx text-hex-7C8699">暂无数据</div>
        </div>
      </div>
    </div>
    <!-- 购物车按钮 -->
    <div v-if="tabindex===0" class="fixed bottom-190rpx right-32rpx" @click.stop="showCar">
      <div class="carshadow relative h-100rpx w-100rpx flex items-center justify-center rounded-50% bg-hex-ffffff">
        <image
          :src="`${cdnUrl}/svgicons/home/goodsCar.svg${imgVersion}`"
          mode="scaleToFill"
          class="h-70rpx w-70rpx"
        />
        <div
          v-if="cartsNum > 0"
          class="font-numberFont absolute right-0 box-border min-h-42rpx min-w-42rpx flex items-center justify-center border-2rpx border-hex-ffffff rounded-50% border-solid bg-hex-C1A670 text-24rpx text-hex-ffffff -top-20rpx">
          {{ cartsNum }}
        </div>
      </div>
    </div>
    <!-- 购物车弹窗 -->
    <div v-if="carshow" class="z-999">
      <tea-goods-car
        :id="addressStores.selectStores.id"
        @close="closeDelDialog"
        @openDialog="opendelpop"
        @delOpenDialog="onlyOpendelpop"
      />
    </div>
    <div class="navBarBox h-167rpx">
      <tab-bar />
    </div>
    <!-- 删除弹窗 -->
    <confirm ref="delpop" />
    <!-- 调起店铺关门弹窗 -->
    <confirm ref="openStoreTipspop" />
    <!-- 优惠券弹窗 -->
    <!-- <uni-popup ref="couponDialog">
      <CouponDialog :dataList="couponDataList" @close="closeCouponDialog" />
    </uni-popup> -->
  </div>
</template>

<script setup lang="ts">
import { useLoginStore } from '@/stores/login'
import { useUserStore } from '@/stores/user'
import { useAddressStore } from '@/stores/address'
import { useTeaStore } from '@/stores/tea'

// const emits = defineEmits(['close'])
let teaStores: any = useTeaStore()
let addressStores: any = useAddressStore()
let location: any = useAddressStore()

const goDetail = (type, id) => {
  if (type === 1) {
    navTo(`/pages-tea/doubleDetails?productId=${id}`)
  } else {
    navTo(`/pages-tea/details?productId=${id}`)
  }
}

const roundeGoDetail = (e) => {
  // if (e.unionFlag === 1) {
  //   navTo(`/pages-tea/doubleDetails?productId=${e.productId}`)
  // } else {
  //   navTo(`/pages-tea/details?productId=${e.productId}`)
  // }
  navTo(`/pages-tea/roundProductDetail?productId=${e.productId}`)
}

const goLogin = () => {
  uni.reLaunch({
    url: '/pages/login',
  })
}
const showCar = () => {
  if (location.selfPickup === 1) {
    let res: any = isaddress()
    if (res) {
      carshow = !carshow
    }
  } else {
    carshow = !carshow
  }
}

// 删除弹窗
const delpop: any = $ref('')
const opendelpop = (data) => {
  delpop.showConfirm('确定清空购物车吗?').then((res) => {
    if (res) {
      uni.$emit('batchDel', data)
    }
  })
}
//开启定位服务弹框
const openPosition = () => {
  uni.showModal({
    title: '授权提示',
    content: '需要获取您的位置信息，请点击下方按钮进入设置页面进行授权',
    confirmText: '去设置',
    success(res) {
      if (res.confirm) {
        uni.openSetting({
          success(res) {
            if (res.authSetting['scope.userLocation']) {
              location.updateEmpower(true)
              location.getPosition({})
            }
          },
          fail(err) {
            console.log(err)
          },
        })
      }
    },
  })
}


const onlyOpendelpop = (data) => {
  delpop.showConfirm('确定删除该商品吗?').then((res) => {
    if (res) {
      uni.$emit('singlgDel', data)
    }
  })
}
const closeDelDialog = () => {
  carshow = false
  getGoodsList()
  getTeaGoosdList()
}

let screenHeight: any = $ref(0)
onLoad(() => {
  uni.hideTabBar()
  // #ifndef H5
  let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
  searchBarTop = menuButtonInfo.top
  rightBar = menuButtonInfo.width

  // #endif
  uni.getSystemInfo({
    success: (res) => {
      screenHeight = res.screenHeight
    },
  })
})

let toView: any = $ref('')

let carshow: any = $ref(false)

let leftScrollHeight: any = $ref(0)
let oldLeftScrollHeight: any = $ref(0)
const leftScroll = (e) => {
  oldLeftScrollHeight = e.detail.scrollTop
}
const leftGoscroll = () => {
  if ([0, 1].includes(leftIndex)) {
    leftScrollHeight = 0
    return
  }
  let tempHight: any = 0
  uni.createSelectorQuery().select('.activecolor').boundingClientRect((data: any) => {
    tempHight = Number(data?.height)
    leftScrollHeight = (Number(leftIndex)) * tempHight
  }).exec()
}

let upHeight: any = $ref(0)
let leftIndex: any = $ref(0)
let scrollLength: any = $ref(0)

const splitScroll = (e) => {
  scrollLength = e.detail.scrollTop
  if (scrollLength <= heightList[0]?.long) {
    leftTabIndex = heightList[0].name
    leftIndex = 0
    return
  }
  if (scrollLength > heightList[heightList.length - 1].long) {
    leftTabIndex = heightList[heightList.length - 1].name
    leftIndex = heightList.length - 1
    leftGoscroll()
    return
  }
  heightList.map((item: any, index: any) => {
    if (Number(heightList[index].long) < scrollLength && scrollLength < Number(heightList[index + 1].long)) {
      leftTabIndex = heightList[index + 1].name
      leftIndex = index + 1
      leftGoscroll()
    }
    return leftTabIndex
  })
}
const onScroll = async (e) => {
  nextTick(() => {
    splitScroll(e)
  })
}

let searchBarTop: any = $ref('24')
let rightBar: any = $ref('100')
let userInfo: any = useUserStore()
// const { useGetInfoData } = useUserStore()
const toptablist = [{ id: 0, text: '自提' }, { id: 1, text: '外送' }]
//店铺数据为空
watch(() => location.selectStores, () => {
  if (Object.keys(location.selectStores).length === 0) {
    navTo('/pages-tea/deliveryWay')
  }
})
watch(() => userInfo.user, async () => {
  await location.getRecentlyStore(location.currentLocation.latitude, location.currentLocation.longitude)
  await getTeaGoosdList()
  await getGoodsList()
})
//判断是否有地址
const isaddress = async () => {
  await addressStores.getListData(userInfo.user.id, 1, 10) //默认先获取10条，用来方便处理没有默认地址取第一条
  await location.defaultaddress(userInfo.user.id)
  if (JSON.stringify(addressStores.selectData) === '{}') {
    uni.showToast({
      title: '请先添加地址!',
      icon: 'none',
    })
    setTimeout(() => {
      navTo('/pages-tea/deliveryWay')
    }, 1800)
    return false
  }
  return true
}

const changeIndex = async (index) => {
  if (index === 0) {
    location.getRecentlyStore(location.currentLocation.latitude, location.currentLocation.longitude)
  } else {
    if (!loginStore.roleId) {
      loginStore.setIsBack(true)
      loginStore.isGoLogin()
      return
    }
    isaddress()
  }
  teaStores.delivery = index
  location.updateSelfPickup(index)
}
console.log(11111111)

const tabList = [{ id: 0, text: '茶饮菜单' }, { id: 1, text: '周边商品' }]
let tabindex: any = $ref(0)
const changetabindex = (index) => {
  if (tabindex === index) {
    return
  }
  tabindex = index
  if (index === 1) {
    roundGoodsList = []
    pageNo = 1
    getRoundList()
  }
}

let leftTabIndex: any = $ref('')
const changeleftTabIndex = (index, idx) => {
  leftTabIndex = index
  toView = index
  leftIndex = idx
  leftGoscroll()
}

let rightGoodsList: any = $ref([])

// 周边商品
let roundGoodsList: any = $ref([])
let pageNo: any = $ref(1)
let isGetGoodsList: any = $ref(false)
// 获取周边商品
const getRoundList = async () => {
  const reqData = {
    method: 'post',
    data: {
      'categoryId': 4,
      'storeId': addressStores.selectStores.id,
      'pageNo': pageNo,
      'pageSize': 10,
    },
    headers: { AppType: 2 },
  }
  const { data, status, error } = await Fetch('/qqyapi/product/product/surround/list', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  if (data.code === 0) {
    roundGoodsList = roundGoodsList.concat(data?.result?.list)
    if (roundGoodsList.length < Number(data?.result?.total)) {
      isGetGoodsList = true
      return
    }
    isGetGoodsList = false
  }
}

// 触底加载更多
onReachBottom(() => {
  if (isGetGoodsList) {
    pageNo++
    getRoundList()
  }
})
let scrollHeight: any = $ref(600)
let downHeight: any = $ref(600)
const loginStore = useLoginStore()


let bannerList: any = $ref([])
// 获取banner
const getBanenrList = async () => {
  const reqData = {
    method: 'post',
    data: {
      'pageNo': 1,
      'pageSize': 10,
    },
    headers: { AppType: 2 },
  }
  const { data, status, error } = await Fetch('/qqyapi/product/banner/list', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  bannerList = data.result.list

}
let noticeList: any = $ref()
// 获取首页通知
const getNotice = async () => {
  const reqData = {
    method: 'post',
    data: {
      'pageNo': 1,
      'pageSize': 10,
    },
    headers: { AppType: 2 },
  }
  const { data, status, error } = await Fetch('/qqyapi/product/notice/list', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  noticeList = data.result.list[0]
}

let tempTeaOrderGoosdList: any = $ref([])
let tabTempList: any = $ref([])

// 获取首页茶饮列表商品
const getTeaGoosdList = async () => {
  const reqData = {
    method: 'post',
    data: {
      'storeId': addressStores.selectStores.id,
    },
    headers: {
      AppType: 2,
      UserId: userInfo?.user?.id || loginStore?.uid,
    },
  }
  const { data, status, error } = await Fetch('/qqyapi/product/category/category/list', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  tempTeaOrderGoosdList = data?.result
  if (tempTeaOrderGoosdList?.length > 0) {
    rightGoodsList = tempTeaOrderGoosdList
    rightGoodsList.forEach((item, index) => {
      rightGoodsList[0].swiperList = '111'
      tabTempList.push(`tab${item.id}`)
      item.id = `tab${item.id}`
    })
    leftTabIndex = rightGoodsList[0].id
    toView = rightGoodsList[0].id
    nextTick(() => {
      getHeight()
    })
  }
}

let heightList: any = $ref([])
const getHeight = () => {
  let upLong: any = 0
  heightList = []
  for (let item of tabTempList) {
    uni.createSelectorQuery().select(`#${item}`).boundingClientRect((data: any) => {
      upLong = Number(upLong) + Number(data?.height)
      heightList.push({
        name: item,
        long: Number(upLong),
      })
    }).exec()
  //许多个...
  }
}
const getInit = async () => {
  let tempList: any = ['#upBox', '#downBox', '.navBarBox', '#swiperHight']
  let tempList2: any = [].concat(tempList)
  downHeight = Number(screenHeight)
  if (tempList.length > 0) {
    tempList.splice(0, 3).forEach((item) => {
      uni.createSelectorQuery().select(item).boundingClientRect((data: any) => {
        downHeight = Number(downHeight) - Number(data?.height)
      }).exec()
    })
    scrollHeight = Number(screenHeight)
    tempList2.forEach((item) => {
      uni.createSelectorQuery().select(item).boundingClientRect((data: any) => {
        scrollHeight = Number(scrollHeight) - data?.height
      }).exec()
    })
    nextTick(() => {
      getHeight()
    })
  }
}

// 获取购物车的总条数
let cartsNum = $ref(0)
const getGoodsList = async () => {
  const reqData = {
    method: 'post',
    data: {
      'storeId': addressStores.selectStores.id,
      'trolleyType': 2,
    },
    headers: { UserId: userInfo?.user?.id },
  }
  const { data, status, error } = await Fetch('/qqyapi/order/trolley/renderTrolleyViewDto', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  if (data.code === 0) {
    const allList = data?.result?.trolleyItemDescDTOList
    cartsNum = allList.reduce((sum, item) => sum + item.amount, 0)
  }
}

const time_to_sec = (time) => {

  if (time !== null) {
    let s: any = ''
    let hour = time.split(':')[0]
    let min = time.split(':')[1]
    let sec = time.split(':')[2]
    s = Number(hour * 3600) + Number(min * 60) + Number(sec)
    return s
  }
}
const getIsClose = () => {
  if (addressStores.selectStores.id) {
    let tempTime: any = new Date()
    let dateHours = tempTime.getHours() //获取小时
    let dateMinutes = tempTime.getMinutes() //获取分钟
    let dateSeconds = tempTime.getSeconds() //获取秒
    tempTime = `${dateHours}:${dateMinutes}:${dateSeconds}`
    tempTime = time_to_sec(tempTime)
    let starTime: any = time_to_sec(addressStores.selectStores.storeStartTime)
    let endTime: any = time_to_sec(addressStores.selectStores.storeEndTime)
    if (Number(tempTime) < Number(endTime) && Number(tempTime) > Number(starTime)) {
      return
    }
    openStoreTipspop.showConfirm(`${addressStores.selectStores?.storeName}打烊啦!换一家吧~`).then((res) => {
      if (res) {
        navTo('/pages-tea/deliveryWay')
        location.updateSelfPickup(0)
      } else {
        navTo('/pages-tea/deliveryWay')
        location.updateSelfPickup(0)
      }
    })
  }
}

const navGoTo = () => {
  if (!loginStore.roleId) {
    loginStore.setIsBack(true)
    loginStore.isGoLogin()
    return
  }
  navTo('/pages-tea/deliveryWay')

}

// // 优惠券弹窗
// let couponDialog: any = $ref('')
// const openCouponDialog = () => {
//   couponDialog.open('center')
// }
// const closeCouponDialog = () => {
//   couponDialog.close()
// }
// let couponDataList: any = $ref([
//   { price: '50', type: '优惠券', experienTime: '2023-12-12 12:00' },
// ])

onMounted(async () => {
  getBanenrList()
  getNotice()
  await location.getPosition({})
  nextTick(() => {
    getInit()
  })
  getIsClose()
})
let openStoreTipspop: any = $ref('')
watch(() => location.currentLocation, async () => {
  if (JSON.stringify(location.currentLocation) !== '{}') {
    await getTeaGoosdList()
    await getGoodsList()
  }
}, { immediate: true })
watchEffect(() => {
  uni.$on('handelEvent', () => {
    tabindex = 0
    getTeaGoosdList()
    getGoodsList()
  })
  uni.$on('updateOrderStoreDo', () => {
    getTeaGoosdList()
  })
  uni.$on('handleUpdateMethod', async () => {
    // 切换取餐方式调用接口
    const reqData = {
      method: 'post',
      data: {
        'deliveryMethod': 1,
        'trolleyType': 2,
        'userAddressId': addressStores.selectData.id,
      },
      headers: { UserId: userInfo.user.id },
    }
    const { status, data, error } = await Fetch('/qqyapi/order/trolley/setTrolleyDeliveryMethod', reqData)
  })
  uni.$on('teaIndexOpenTeaGoodsCarPop', () => {
    carshow = true
    getTeaGoosdList()
    getGoodsList()
  })
})
</script>

<route lang="json">
{"style":{"disableScroll":true}}
</route>

<style lang="scss">
.home{
  .multiLine-hiddle{
    overflow : hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }

  .will-change{
    will-change: transform
  }

  .scrolldemo{
    scrollbar-width: none; /* firefox */
    -ms-overflow-style: none; /* IE 10+ */
    overflow-x: hidden;
    overflow-y: auto;
  }

  ::-webkit-scrollbar {
    display: none; /* Chrome Safari */
  }

  .triangle{
    width: 0;
    height: 0;
    border-color: transparent; /* 上下颜色 左右颜色 */
    border-width: 24rpx ;
    border-bottom-color: #fff;
    border-style: solid;
  }

  .borderShadow{
    box-shadow: 2rpx 2rpx 6rpx 0rpx rgb(24 167 134 / 26%);
  }

  .carshadow{
    box-shadow: 0rpx 4rpx 20rpx 0rpx rgb(0 0 0 / 9%);
  }

  .scale7{
    transform: scale(.8);
    font-size: 18rpx;
  }

  .activecolor{
    color: #333;
  }

  .tagLine::after{
    position: absolute;
    content: '';
    height:14rpx;
    width:2rpx;
    top: 10rpx;
    right: -10rpx;
    background-color: #7c8699;
  }

  .tagLine:last-child::after{
    height:0rpx;
    width:0rpx;
  }

  ::v-deep(.uni-noticebar){
    padding: 0rpx !important;

    .uni-noticebar__content-text{
      font-size: 24rpx !important;
    }
  }
}

</style>

